package org.zero.onlinesubject.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.zero.onlinesubject.common.param.Chunk;
import org.zero.onlinesubject.common.vo.FileVo;
import org.zero.onlinesubject.common.vo.Result;
import org.zero.onlinesubject.entity.SystemFile;
import org.zero.onlinesubject.service.SystemFileService;
import org.zero.onlinesubject.utils.IDWorker;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/file/api")
public class FileController {

    @Resource
    private SystemFileService fileService;

    @GetMapping("/getBizID")
    public Result<String> createBizID(){
        return Result.ok(IDWorker.createFID());
    }

    @GetMapping("/getFile")
    public Result<List<SystemFile>> getFile(String bizId,String fileType){
        List<SystemFile> list = fileService.getFileByBizId(bizId,fileType);
        return list.isEmpty() ? Result.error(500,"请求的资源不存在"):Result.ok(list);
    }

    // 小文件上传
    @PostMapping("/upload")
    public Result<List<FileVo>> upload(@RequestParam("files") MultipartFile[] files, @RequestParam("bizId") String bizId) throws Exception {
        List<FileVo> fileList = fileService.uploadFile(files, bizId);
        if(fileList.isEmpty()){
            return Result.error(500,"文件上传失败,请重试");
        }
        return Result.ok(fileList);
    }

    // 大文件上传
    @PostMapping("/bigFileUpload")
    public Result<String> bigFileUpload(@ModelAttribute Chunk chunk) throws IOException {
        Boolean flag = fileService.bigFileUpload(chunk);
        return flag ? Result.ok("分片: "+chunk.getChunkNum() + " 上传成功！") : Result.error(500,"分片: "+chunk.getChunkNum() + " 上传失败！");
    }

    @GetMapping("/success")
    public Result<String> uploadFinish(String bizId,String filename,String md5,Long totalSize,Boolean fromLive){
        Boolean flag = fileService.uploadFinish(bizId,filename,md5,totalSize,fromLive);
        Result result = null;

        if(fromLive){
            result = flag ? Result.ok("文件保存成功,开始在后台对文件进行转码"):Result.error(500,"文件保存失败");
        }else{
            result = flag ? Result.ok("文件上传成功!") : Result.error(500,"文件上传失败");
        }
        return result;
    }

    /*
    @GetMapping("/UploadInfo")
    public ResponseEntity<Map<Integer,Integer>> getUploadInfo(String md5) throws IOException {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String dirPath = continuePath + "/" + date;
        String filePath = dirPath + "/" + md5 + ".txt";
        if(Files.notExists(Paths.get(dirPath))){
            return ResponseEntity.ok(null);
        }
        if(Files.notExists(Paths.get(filePath))){
            return ResponseEntity.ok(null);
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        List<String> list = Files.readAllLines(Path.of(filePath));
        list.forEach(item->{
            String[] strArr = item.split(",");
            map.put(Integer.parseInt(strArr[0]),Integer.parseInt(strArr[1]));
        });
        return ResponseEntity.ok(map);
    }

    // 断点续传
    @PostMapping("/breakpoint")
    public ResponseEntity<String> breakpointUpload(MultipartFile file,String md5) throws IOException {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String dirPath = continuePath + "/" + date;
        String ext = StringUtils.getFilenameExtension(file.getOriginalFilename());
        if(ext == null || StringUtils.isEmpty(ext)) return ResponseEntity.badRequest().body("请上传格式正确的文件");
        String filePath = dirPath + "/" + md5 + "." + ext;
        String fileMd5Path = filePath.replace(ext,"txt");

        if(Files.notExists(Paths.get(dirPath))){
            Files.createDirectory(Paths.get(dirPath));
        }
        if(Files.notExists(Paths.get(filePath))){
            Files.createFile(Paths.get(filePath));
            Files.createFile(Paths.get(fileMd5Path));
        }
        RandomAccessFile raf = null;
        RandomAccessFile md5Raf = null;
        int pLen = 0;
        int chunk = 1;
        try {
            raf = new RandomAccessFile(new File(filePath),"rw");
            md5Raf = new RandomAccessFile(new File(fileMd5Path),"rw");
            InputStream fis = file.getInputStream();

            byte[] buff = new byte[8196];
            int readLen;

            while((readLen = fis.read(buff))!=-1){
                raf.write(buff,0,readLen);
                pLen += readLen;
            }
            return ResponseEntity.ok("文件上传成功");
        }catch(Exception e){
            e.printStackTrace();
            log.error("文件传输中断");
        } finally {
            if(raf!=null){
                raf.close();
            }
            if(md5Raf!=null){
                String str = chunk + "," + pLen;
                md5Raf.writeChars(str);
            }
        }
        return ResponseEntity.ok("文件上传成功");
    }
    */
}
